//获取数据库中用户的信息

package zut.DAO.impl;

import com.mysql.cj.QueryResult;
import zut.DAO.UserDAO;
import zut.DO.UserDO;
import zut.util.JDBCUtil;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;


public class UserDAOImpl implements UserDAO {
    @Override
    public UserDO getUserDO(String userid) {
        //第一步获取数据库连接
        Connection conn = JDBCUtil.getConnction();
        String sql = "select * from user where userid = ?";//不能使用Statement
        PreparedStatement ps = null;
        try {
            assert conn != null;
            ps =  conn.prepareStatement(sql);
            ps.setString(1,userid);
            ResultSet rs = ps.executeQuery();
            while(rs.next()){
                String usernamebyDB = rs.getString("username");
                String passwordbyDB = rs.getString("password");
                return new UserDO(userid,usernamebyDB,passwordbyDB);
            }
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
        return null;
    }

    @Override
    public boolean insertUserDO(UserDO user) {
        Connection conn = JDBCUtil.getConnction();
        String sql = "INSERT INTO user (username,password,userid) VALUES (?,?,?);";//不能使用Statement
        PreparedStatement ps = null;
        try {
            assert conn != null;
            ps =  conn.prepareStatement(sql);
            ps.setString(1,user.getUsername());
            ps.setString(2,user.getPassword());
            ps.setString(3,user.getUserid());
            ps.execute();
            return true;
            } catch (SQLException e) {
            return false;
        }
    }

    @Override
    public boolean deleteUserDO(UserDO user) {
        Connection conn = JDBCUtil.getConnction();
        String username = user.getUsername();
        String sql = "delete from user where username =?";//不能使用Statement
        PreparedStatement ps = null;
        try {
            assert conn != null;
            ps =  conn.prepareStatement(sql);
            ps.setString(1,username);
            ps.execute();
            return true;
        } catch (SQLException e) {
            return false;
        }
    }
}
